#!/bin/bash

# 这个脚本用于在显示回复前将内容保存到临时目录
# 参数1: 要下载的附件URL列表（可选）
# 参数2: 临时目录路径（可选，默认使用/tmp）

TEMP_DIR="${2:-/tmp}"
ATTACHMENT_URLS=("$1")

# 创建临时目录
sanitized_model=$(echo "$rfm_AI_MODEL_NAME" | sed 's/[:/\*?<>|\"]/_/g')
timestamp=$(date +%Y%m%d_%H%M%S)
temp_dirname="rfmAI_${sanitized_model}___${timestamp}"
full_temp_path="$TEMP_DIR/$temp_dirname"

mkdir -p "$full_temp_path"
cd "$full_temp_path"

# 保存原始响应和请求
echo "$RESPONSE" > .rfmAI_latest_response.json
echo "$REQUEST_JSON" > .rfmAI_latest_request.json


# 函数：根据文件内容修正文件后缀
correct_file_extension() {
    local file="$1"
    
    if [ ! -f "$file" ]; then
        echo "错误: 文件不存在: $file" >&2
        return 1
    fi
    
    # 使用 file 命令检测文件类型
    local file_type
    file_type=$(file -b --mime-type "$file" 2>/dev/null)
    
    if [ $? -ne 0 ] || [ -z "$file_type" ]; then
        echo "警告: 无法检测文件类型: $file" >&2
        return 1
    fi
    
    # 获取当前文件后缀（小写）
    local current_ext
    current_ext=$(echo "${file##*.}" | tr '[:upper:]' '[:lower:]')
    
    # 映射 MIME 类型到文件后缀
    local new_ext=""
    case "$file_type" in
        "image/jpeg")
            new_ext="jpg"
            ;;
        "image/png")
            new_ext="png"
            ;;
        "image/gif")
            new_ext="gif"
            ;;
        "image/webp")
            new_ext="webp"
            ;;
        "image/bmp")
            new_ext="bmp"
            ;;
        "image/tiff")
            new_ext="tiff"
            ;;
        "image/svg+xml")
            new_ext="svg"
            ;;
        "application/pdf")
            new_ext="pdf"
            ;;
        "text/plain")
            new_ext="txt"
            ;;
        "application/json")
            new_ext="json"
            ;;
        *)
            # 对于未知类型，保持原样
            echo "信息: 未知文件类型 '$file_type'，保持原文件名: $file" >&2
            return 0
            ;;
    esac
    
    # 如果检测到的类型与当前后缀不匹配，则修正
    if [ -n "$new_ext" ] && [ "$current_ext" != "$new_ext" ]; then
        local base_name="${file%.*}"
        local new_filename="${base_name}.${new_ext}"
        
        # 避免文件名冲突
        local counter=1
        local final_new_filename="$new_filename"
        while [ -e "$final_new_filename" ]; do
            final_new_filename="${base_name}_${counter}.${new_ext}"
            ((counter++))
        done
        
        if mv "$file" "$final_new_filename"; then
            echo "修正文件后缀: $file -> $final_new_filename (检测到类型: $file_type)" >&2
            echo "$final_new_filename"
        else
            echo "错误: 无法重命名文件: $file -> $final_new_filename" >&2
            echo "$file"
        fi
    else
        # 后缀匹配或无需修改
        echo "$file"
    fi
}



# 下载附件（如果有）
ATTACHMENT_INFO=""
if [ ${#ATTACHMENT_URLS[@]} -gt 0 ] && [ -n "${ATTACHMENT_URLS[0]}" ]; then
    for url in "${ATTACHMENT_URLS[@]}"; do
        if [ -n "$url" ] && [ "$url" != "null" ]; then
            echo "下载附件: $url"
            filename="attachment_${timestamp}_$(basename "$url" | sed 's/[^a-zA-Z0-9._-]/_/g')"
            if curl -sS -f -o "$filename" "$url"; then
                # 下载成功后，检查并修正文件后缀
                corrected_filename=$(correct_file_extension "$filename")
                echo "附件已下载: $corrected_filename"
                ATTACHMENT_INFO="$ATTACHMENT_INFO\n![附件]($corrected_filename)"
            else
                echo "附件下载失败: $url"
                ATTACHMENT_INFO="$ATTACHMENT_INFO\n附件URL: $url"
            fi
        fi
    done
fi

# 提取使用情况信息
USAGE_INFO=""
if echo "$RESPONSE" | jq -e '.output.usage' > /dev/null 2>&1; then
    IMAGE_COUNT=$(echo "$RESPONSE" | jq -r '.output.usage.image_count // empty')
    WIDTH=$(echo "$RESPONSE" | jq -r '.output.usage.width // empty')
    HEIGHT=$(echo "$RESPONSE" | jq -r '.output.usage.height // empty')
    
    if [ ! -z "$IMAGE_COUNT" ]; then
        USAGE_INFO="生成图像数量: $IMAGE_COUNT"
        if [ ! -z "$WIDTH" ] && [ ! -z "$HEIGHT" ]; then
            USAGE_INFO="$USAGE_INFO\n图像分辨率: ${WIDTH}x${HEIGHT}"
        fi
    fi
fi

# 提取请求ID
REQUEST_ID=$(echo "$RESPONSE" | jq -r '.request_id // empty')

# 创建markdown文件
cat <<EOF > "rfmAI.md"
# 用户提示词 #
$rfm_AI_MODEL_prompt

# 附加文件 #
$(if [[ "$confirm_multimodal" =~ ^[Yy]$ ]] && [[ ${#MULTIMODAL_FILES[@]} -ne 0 ]]; then printf '%s\n' "${MULTIMODAL_FILES[@]}" ; fi)

# 模型回复内容 #
$RESULT

$(if [ ! -z "$ATTACHMENT_INFO" ]; then
    echo -e "\n# 生成附件 #$ATTACHMENT_INFO"
fi)

$(if [ ! -z "$USAGE_INFO" ]; then
    echo -e "\n# 使用情况 #\n$USAGE_INFO"
fi)

# 请求URL #
$rfm_AI_MODEL_HOST_URL

# 模型名称 #
$rfm_AI_MODEL_NAME

# 温度 #
$rfm_AI_MODEL_TEMPERATURE

# 历史ID #
$(echo "$RESPONSE_ID_ARRAY")

# 请求ID #
$(if [ -z "$REQUEST_ID" ]; then
    echo "警告: 未提供REQUEST_ID"
else
    echo "$REQUEST_ID"
fi)

# 反馈 #

EOF


# 设置环境变量供后续脚本使用
export RFM_TEMP_SAVE_PATH="$full_temp_path"
echo "临时保存路径: $full_temp_path" >&2
